/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AliperWindow.java
 *
 * Created on 2009-11-13, 14:41:43
 */

package com.alibaba.aliper.client.view;

import java.awt.Color;
import java.util.HashMap;
import java.util.HashSet;

import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;

import org.jfree.chart.ChartPanel;

import com.alibaba.aliper.client.model.IModelAccess;
import com.alibaba.aliper.core.chart.AliperChart;
import com.alibaba.aliper.core.chart.IFill;

/**
 *
 * @author cori-chenxx
 */
public class AliperWindow extends javax.swing.JFrame implements IView {

    /** Creates new form AliperWindow */
    public AliperWindow() {
        initComponents();
        this.setSize(900, 550);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jScrollPane2 = new javax.swing.JScrollPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar1.setRollover(true);

        jButton1.setText("refresh");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton1);

        jButton2.setText("restart");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);

        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTree1);

        jSplitPane1.setLeftComponent(jScrollPane1);
        jSplitPane1.setRightComponent(jScrollPane2);

        jMenu1.setText("File");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("login");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 657, Short.MAX_VALUE)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 657, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTree jTree1;
    // End of variables declaration
    
    private void jTree1ValueChanged(TreeSelectionEvent e) {
    	Object[] nodes = e.getPath().getPath();
    	if(nodes.length == 3){
    		String agent = nodes[1].toString();
    		String chart = nodes[2].toString();
    		String chartKey = agent + "$$" + chart;
    		ChartPanel chartPanel = null;
    		ChartStore sc =  this.charts.get(chartKey);
    		if(sc != null){
    			chartPanel =sc.chartPanel;
    			jScrollPane2.setViewportView(chartPanel);
    			System.out.println("agent:"+agent + " chart:"+chart);
    		} else {
    			System.err.println("agent:"+agent + " chart:"+chart + " not existed");
    		}
    	}
	}
    private AliperLoginWindow loginWindow = new AliperLoginWindow();
	private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        System.out.println("mem clicked");
        loginWindow.setVisible(true);
    }                                          

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    	this.model.refresh();
    	this.updateMenu();
    	System.out.println("button refresh clicked");
    }                      
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    	this.model.restart();
    	this.model.refresh();
    	this.updateMenu();
    	charts = new HashMap<String, ChartStore>();
    	System.out.println("button restart clicked");
    }        
    @Override
    public void setVisible(boolean b) {
    	super.setVisible(b);
    	if(this.model.getServiceURL() == null)
    		this.loginWindow.setVisible(true);
    }
    
	public void fill(String agent, String chart, String line, long time,
			double data) {
		AliperChart aliperChart = null;
		String chartKey = agent +"$$"+ chart;
		if(this.charts.containsKey(chartKey)){
			aliperChart = this.charts.get(chartKey).aliperChart; 
		} else {
			aliperChart = new AliperChart(agent+"-"+chart, "alibaba-plat-cori.chenxx", Color.lightGray,true);
			this.charts.put(chartKey, new ChartStore(aliperChart, new ChartPanel(aliperChart.getChart())));
			this.updateMenu();
		}
		IFill fill = aliperChart.getLine(line, false);
		fill.fill(time, data);
	}
	private void updateMenu() {
		//根据charts的key更新菜单内容
		HashMap<String, DefaultMutableTreeNode> agents = new HashMap<String, DefaultMutableTreeNode>();
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("agents") ;
		HashSet<String> addedCharts = new HashSet<String>();
		for(String key : this.model.getChartSpecfics()){
			String[] arr =  key.split("\\$\\$");
			if(arr.length > 1){
				String agent = arr[0];
				String chart = arr[1];
				DefaultMutableTreeNode agentNode = null;
				if(agents.containsKey(agent)){
					agentNode = agents.get(agent);
				} else {
					agentNode = new DefaultMutableTreeNode(agent);
					agents.put(agent, agentNode);
					root.add(agentNode);
				}
				if(!addedCharts.contains(agent+"$$"+chart)){
					agentNode.add(new DefaultMutableTreeNode(chart));
					addedCharts.add(agent+"$$"+chart);
				}
				
			}
		}
		TreeModel model = new DefaultTreeModel(root);
		this.jTree1.setModel(model);
	}

	private HashMap<String, ChartStore> charts = new HashMap<String, ChartStore>();
	static class ChartStore{
		public ChartStore(AliperChart aliperChart,ChartPanel chartPanel){
			this.aliperChart = aliperChart;
			this.chartPanel = chartPanel;
		}
		AliperChart aliperChart = null;
		ChartPanel chartPanel = null;
	}
	
	private IModelAccess model = null;
	public void setModel(IModelAccess model){
		this.model = model;
		this.loginWindow.setModel(model);
	}
	
       /**
	    * @param args the command line arguments
	    */
	    public static void main(String args[]) {
	    	AliperWindow window  = new AliperWindow();
	    	window.setVisible(true);
	    	System.out.println("over");
	    }

}
